package com.ktwlrj.securitycenter.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.google.common.base.Joiner;
import com.ktwlrj.core.base.ActionResult;
import com.ktwlrj.core.config.properties.AppProperty;
import com.ktwlrj.core.constant.Constant;
import com.ktwlrj.core.constant.ResultCode;
import com.ktwlrj.core.exception.ActionException;
import com.ktwlrj.core.feign.FrameworkClient;
import com.ktwlrj.core.feign.McClient;
import com.ktwlrj.core.feign.args.SysCredentialsConfigArgs;
import com.ktwlrj.core.feign.dto.BusiSimpleInfo;
import com.ktwlrj.core.feign.dto.DataAuthRuleResultModel;
import com.ktwlrj.core.feign.dto.MemberDto;
import com.ktwlrj.core.feign.dto.PermissionInfo;
import com.ktwlrj.core.util.ContextHolderUtils;
import com.ktwlrj.securitycenter.service.SystemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 授权相关服务层接口实现
 *
 * @author zhouxuanhong
 * @date 2019-07-18 10:43
 * @since JDK1.8
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SystemServiceImpl implements SystemService {
    private final McClient mcClient;
    private final AppProperty property;
    private final FrameworkClient baseClient;
    private final ContextHolderUtils contextHolderUtils;
    @Value("${framework.system-id}")
    private String systemId;

    @Override
    public List<PermissionInfo> auth(HttpServletRequest request) throws RuntimeException {
        HttpSession session = request.getSession();
        // 获取用户菜单权限
        return getAuthMenuByToken(session);
    }


    @Override
    public String takeNumber(String tnRuleCode) throws RuntimeException {
        ActionResult<String> result = baseClient.takeNumber(tnRuleCode, "", systemId);
        if (!result.isSuccess()) {
            throw new ActionException(ResultCode.API_PARAM_ERROR.getValue(), result.getMessage());
        }
        return result.getData();
    }


    @Override
    public Object businessRule(String dictionaryCode) throws RuntimeException {
        ActionResult<JSONArray> result = baseClient.getDic(systemId, dictionaryCode, "");
        if (!result.isSuccess()) {
            throw new ActionException(ResultCode.API_PARAM_ERROR.getValue(), result.getMessage());
        }
        return result.getData();
    }


    @Override
    public List<SysCredentialsConfigArgs> getBusiConfigOrCredentials(String busiId) throws RuntimeException {
        List<SysCredentialsConfigArgs> credentialsConfigArgsList = new ArrayList<>();
        ActionResult<List<SysCredentialsConfigArgs>> result = baseClient.getBusiConfigOrCredentials(systemId, busiId, "");
        if (!result.isSuccess()) {
            throw new ActionException(ResultCode.API_PARAM_ERROR.getValue(), result.getMessage());
        }
        return result.getData() == null ? credentialsConfigArgsList : result.getData();
    }


    @Override
    public List<MemberDto> getListMemberByOrgId() throws RuntimeException {
        ActionResult<Object> result = mcClient.getListMemberByOrgId(contextHolderUtils.getCurrentOrgId(), 0, null, null);
        if (!result.isSuccess()) {
            throw new ActionException(ResultCode.API_REJECTED.getValue(), "会员中心接口异常=》" + result.getMessage());
        }
        return (List<MemberDto>) result.getData();
    }


    /**
     * 通过授权token获取用户菜单权限
     *
     * @param session ${@link HttpSession}
     * @return List<PermissionInfo> ${@link List<PermissionInfo>}
     * @author zhouxuanhong
     * @date 2019-07-18 11:19
     */
    private List<PermissionInfo> getAuthMenuByToken(HttpSession session) {
        List<PermissionInfo> menus;
        try {
            ActionResult<List<PermissionInfo>> authMenuByToken = baseClient.getMemberUserPermission(contextHolderUtils.getOpenId(), systemId, contextHolderUtils.getCurrentOrgId());
            log.debug("----------SystemServiceImpl---------->getAuthMenuByToken:{}", authMenuByToken);
            if (!authMenuByToken.isSuccess()) {
                menus = Collections.emptyList();
            } else {
                menus = authMenuByToken.getData();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("----------SystemServiceImpl---------->getAuthMenuByToken:{}", e.getMessage());
            menus = Collections.emptyList();
        }
        session.setAttribute(Constant.USER_AUTH_MENU, menus);
        return menus;
    }


    @Override
    public List<BusiSimpleInfo> getBusiList(String authCode) throws RuntimeException {
        List<String> busiIdList = getDataAuth(authCode);
        String busiIds = Joiner.on(",").join(busiIdList);
        ActionResult<List<BusiSimpleInfo>> busiList = baseClient.getBusiList(busiIds);
        if (!busiList.isSuccess()) {
            throw new ActionException(ResultCode.API_ERROR.getValue(), "基础平台接口异常：" + busiList.getMessage());
        }
        List<BusiSimpleInfo> result = new ArrayList<>();
        if (busiList.getData() != null && busiList.getData().size() > 0) {
            result.addAll(busiList.getData());
        }
        return result;
    }

    /**
     * 根据数据权限编码获取数据权限
     *
     * @param authCode 数据权限编码
     * @return
     * @throws RuntimeException
     */
    private List<String> getDataAuth(String authCode) throws RuntimeException {
        ActionResult<List<DataAuthRuleResultModel>> result = baseClient.getDataAuth(authCode, null);
        if (!result.isSuccess()) {
            throw new ActionException(ResultCode.API_ERROR.getValue(), "基础平台接口异常：" + result.getMessage());
        }
        if (result.getData() == null || result.getData().size() <= 0) {
            throw new ActionException(ResultCode.DATABASE_NODATA.getValue(), "基础平台接口异常：数据权限规则不存在");
        }
        List<String> busiIdList = new ArrayList<>();
        for (DataAuthRuleResultModel item : result.getData()) {
            busiIdList.addAll(item.getValues());
        }
        return busiIdList;
    }
}
